import { getToken } from '@/utils/auth';
import { ElNotification } from 'element-plus';
import useNoticeStore from '@/store/modules/notice';
import mapNoticeStore from '@/store/modules/mapNotice';

const message = '';

// 初始化
export const initSSE = (url: any) => {
  url = url + '?Authorization=Bearer ' + getToken() + '&clientid=' + import.meta.env.VITE_APP_CLIENT_ID;
  const {
    data,
    error
  } = useEventSource(url, [], {
    autoReconnect: {
      retries: 10,
      delay: 3000,
      onFailed() {
        console.log('Failed to connect after 10 retries');
      }
    }
  });

  watch(error, () => {
    console.log('SSE connection error:', error.value);
    error.value = null;
  });
  const isJSON = (str) => {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  };
  watch(data, () => {
    console.log('-------', data.value, '-------');
    
    if (!data.value) { return; }
    // 判断是否为安防地图消息提醒  是否json
    let flag = false;
    if (isJSON(data.value)) {
      const temp = JSON.parse(data.value);
      flag = true;
      // 判断temp是否包含alarmRecordId
      console.log('temp.alarmRecordId', temp.alarmRecordId);
      console.log('temp.cameraPatrolTaskExecutorId', temp.cameraPatrolTaskExecutorId);
      if (temp.alarmRecordId) {
        // debugger
        mapNoticeStore().addNotices({
          message: temp.alarmAddress,
          time: new Date(temp.alarmTime).toLocaleString(),
          type: temp.alarmType,
          grade: temp.alarmGrade,
          alarmRecordId: temp.alarmRecordId
        });
      } else {
        mapNoticeStore().addNotices({
          message: temp.cameraPatrolTaskExecutorId,
          time: new Date(temp.startTime).toLocaleString(),
          type: '',
          grade: '',
          alarmRecordId: undefined
        });
      }
    }
    if (flag) { return; }
    useNoticeStore().addNotice({
      message: data.value,
      read: false,
      time: new Date().toLocaleString()
    });

    ElNotification({
      title: '消息',
      message: data.value,
      type: 'success',
      duration: 0
    });
    data.value = null;
  });
};

